﻿using Autofac;
using Autofac.Integration.Mvc;
using AutofacProject.Class;
using AutofacProject.Entity;
using AutofacProject.Interface;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Web;
using System.Web.Mvc;

namespace AutofacProject.App_Start
{
    public class AutofacConfig
    {
        public static void AutofacRegister()
        {
            var builder = new ContainerBuilder();
            //1.单个依赖注入
            builder.RegisterType<Benz>().As<Icar>();
            builder.RegisterType<AutofacDbContext>().AsSelf().InstancePerLifetimeScope();
            Assembly asmService = Assembly.Load("AutofacProject.Service");
            //注入所有非抽象成员
            builder.RegisterAssemblyTypes(asmService).Where(t => !t.IsAbstract).AsImplementedInterfaces().PropertiesAutowired();
            Assembly asmRepository = Assembly.Load("AutofacProject.Repository");
            //注入所有非抽象成员
            builder.RegisterAssemblyTypes(asmRepository).Where(t => !t.IsAbstract).AsImplementedInterfaces().PropertiesAutowired();

            //2.依赖注入当前应用程序下的所有Controller
            builder.RegisterControllers(typeof(MvcApplication).Assembly).PropertiesAutowired();//指定注入方式为属性注入
            //容器构建
            var container = builder.Build();
            //解析器替换
            DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
        }
    }
}